/*
Copyright [2020] [https://www.stylefeng.cn]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Guns采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Guns源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/stylefeng/guns-separation
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/stylefeng/guns-separation
6.若您的项目无法满足以上几点，可申请商业授权，获取Guns商业授权许可，请在官网购买授权，地址为 https://www.stylefeng.cn
 */
package cn.stylefeng.guns.sys.modular.auth.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.stylefeng.guns.core.consts.CommonConstant;
import cn.stylefeng.guns.core.context.constant.ConstantContextHolder;
import cn.stylefeng.guns.core.context.login.LoginContextHolder;
import cn.stylefeng.guns.core.exception.AuthException;
import cn.stylefeng.guns.core.exception.enums.AuthExceptionEnum;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.core.pojo.response.SuccessResponseData;
import cn.stylefeng.guns.sys.core.enums.LogSuccessStatusEnum;
import cn.stylefeng.guns.sys.core.log.LogManager;
import cn.stylefeng.guns.sys.modular.auth.constant.Constant;
import cn.stylefeng.guns.sys.modular.auth.service.AuthService;
import cn.stylefeng.guns.sys.modular.user.entity.SysUser;
import cn.stylefeng.guns.sys.modular.user.service.SysUserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.*;

import java.util.Base64;
import java.util.List;

/**
 * 登录控制器
 *
 * @author xuyuxiang
 * @date 2020/3/11 12:20
 */
@RestController
public class SysLoginController {

    private static final Logger LOGGER = org.apache.logging.log4j.LogManager.getLogger(SysLoginController.class);

    @Resource
    private AuthService authService;

    @Resource
    private SysUserService sysUserService;


    /**
     * 校验票据
     *
     * @author zhanggq
     * @date 2022/12/13 15:52
     */
    @PostMapping("/sso/client/checkTicket")
    public ResponseData checkTicket(@RequestBody Dict dict) {
        String account = dict.getStr("account");
        String ticket = dict.getStr("ticket");
        String from = dict.getStr("from");

        return authService.clientCheckTicket(from, account, ticket);
    }


    /**
     * 检查登录状态
     *
     * @author zhanggq
     * @date 2022/12/13 15:52
     */
    @PostMapping("/sso/client/checkLoginStatus")
    public ResponseData ssoCheckLoginStatus(HttpServletRequest request) {
        return authService.checkUserLoginStatus(request);
    }

    /**
     * 为其他系统提供的录接口
     *
     * @author zhanggq
     * @date 2022/12/13 15:52
     */
    @PostMapping("/isfm/node-api/login")
    public ResponseData otherSyslogin(@RequestBody Dict dict) {
        String account = dict.getStr("account");
        String password = dict.getStr("password");
        String tenantCode = dict.getStr("tenantCode");
        String locale = dict.getStr("locale");
        //如果系统开启了多租户开关，则添加租户的临时缓存
        if (ConstantContextHolder.getTenantOpenFlag()) {
            authService.cacheTenantInfo(tenantCode);
        }

        String token = authService.login(account, password, locale);
        return new SuccessResponseData(token);
    }

    /**
     * 为其他系统提供的登录接口(对外提供一个端口时)
     *
     * @author zhanggq
     * @date 2023/7/19 15:52
     */
    @PostMapping("/api/isfm/node-api/login")
    public ResponseData otherSysloginForOnePort(@RequestBody Dict dict) {
        String account = dict.getStr("account");
        String password = dict.getStr("password");
        String tenantCode = dict.getStr("tenantCode");
        String locale = dict.getStr("locale");
        //如果系统开启了多租户开关，则添加租户的临时缓存
        if (ConstantContextHolder.getTenantOpenFlag()) {
            authService.cacheTenantInfo(tenantCode);
        }

        String token = authService.login(account, password, locale);
        return new SuccessResponseData(token);
    }

    /**
     * @description 免验证码登陆
     * @author kongtao
     * @date 2023/2/15 8:49
     **/
    @PostMapping("/sys/login")
    public ResponseData sysLogin(@RequestBody Dict dict) {
        String account = dict.getStr("account");
        String password = dict.getStr("password");
        String tenantCode = dict.getStr("tenantCode");
        String locale = dict.getStr("locale");
        //如果系统开启了多租户开关，则添加租户的临时缓存
        if (ConstantContextHolder.getTenantOpenFlag()) {
            authService.cacheTenantInfo(tenantCode);
        }

        String token = authService.login(account, password, locale);
        return new SuccessResponseData(token);
    }

    /**
     * 账号密码登录
     *
     * @author xuyuxiang
     * @date 2020/3/11 15:52
     */
    @PostMapping("/login")
    public ResponseData login(@RequestBody Dict dict) {
        String account = dict.getStr("account");
        String password = dict.getStr("password");
        String tenantCode = dict.getStr("tenantCode");
        String locale = dict.getStr("locale");
        /*if(StrUtil.isNotEmpty(account)) {
            String[] subjects = subject.split(",");
            String userName = "";
            for(String sub : subjects) {
                if(sub.contains("CN=")) {
                    userName = sub.substring(sub.indexOf("=") + 1);
                    try {
                        account = new String(authService.decrypt(Base64.getDecoder().decode(account), Constant.PRIVATE_KEY));
                    } catch (Exception e) {
                        LogManager.me().executeLoginLog(userName, LogSuccessStatusEnum.FAIL.getCode(), AuthExceptionEnum.ACCOUNT_CERT_FAIL.getMessage());
                        throw new AuthException(CommonConstant.ACCOUNT_CERT_FAIL, locale);
                    }

                    if(!account.equals(userName)) {
                        // 此时登录的账号可能是邮箱，使用邮箱查询登录用户的信息
                        List<SysUser> userList = sysUserService.getUserByEmail(account);
                        if(CollectionUtil.isNotEmpty(userList)) {
                            SysUser sysUser = userList.get(0);
                            if(sysUser != null && sysUser.getAccount().equals(userName)) {
                                account = sysUser.getAccount();
                            } else {
                                LogManager.me().executeLoginLog(account, LogSuccessStatusEnum.FAIL.getCode(), AuthExceptionEnum.ACCOUNT_CERT_INCONSISTENT.getMessage());
                                throw new AuthException(CommonConstant.ACCOUNT_CERT_INCONSISTENT, locale);
                            }
                        } else {
                            LogManager.me().executeLoginLog(account, LogSuccessStatusEnum.FAIL.getCode(), AuthExceptionEnum.ACCOUNT_CERT_INCONSISTENT.getMessage());
                            throw new AuthException(CommonConstant.ACCOUNT_CERT_INCONSISTENT, locale);
                        }
                    }

                    certAuth = true;
                    break;
                }
            }

            if(StrUtil.isNotEmpty(password)) {
                account = dict.getStr("account");
                certAuth = false;
            }
        }*/

        //如果系统开启了多租户开关，则添加租户的临时缓存
        if (ConstantContextHolder.getTenantOpenFlag()) {
            authService.cacheTenantInfo(tenantCode);
        }

        String token = authService.login(account, password, locale);
        return new SuccessResponseData(token);
    }

    /**
     * 退出登录
     *
     * @author xuyuxiang
     * @date 2020/3/16 15:02
     */
    @GetMapping("/logout")
    public void logout() {
        authService.logout();
    }

    /**
     * 获取当前登录用户信息
     *
     * @author xuyuxiang, fengshuonan
     * @date 2020/3/23 17:57
     */
    @GetMapping("/getLoginUser")
    public ResponseData getLoginUser() {
        return new SuccessResponseData(LoginContextHolder.me().getSysLoginUserUpToDate());
    }

}
